#include "map.h"
#include <cstdio>
#include <cassert>
#include <cstring>

#ifndef NDEBUG
#	include "map.inl"
#endif

Map::Map()
: m_iWidth(0), m_iHeight(0), m_pTiles(NULL)
{

}

Map::~Map()
{
	Free();
}

void Map::Free()
{
	if (m_pTiles) {
		delete[] m_pTiles;
		m_pTiles = NULL;
	}
}

void Map::New(short width, short height)
{
	Free();

	m_iWidth = width;
	m_iHeight = height;

	m_pTiles = new Tile[m_iHeight * m_iWidth];
	for (int y = 0; y < m_iHeight; y++) {
		for (int x = 0; x < m_iWidth; x++) {
			Tile& tile = m_pTiles[y * m_iWidth + x];
			tile.iGroundId	= BLANK_TILE + 1;
			tile.iSkyId		= BLANK_TILE;
			tile.iTrapId	= BLANK_TRAP;
			tile.bBlocked	= false;
		}
	}
}

bool Map::Load(char const *filename)
{
	FILE *file = fopen(filename, "rb");
	if (file != NULL) {
		fread(m_sName, sizeof(char), MAX_NAME, file);
		m_sName[MAX_NAME - 1] = '\0';

		fread(&m_iWidth,  sizeof(short), 1, file);
		fread(&m_iHeight, sizeof(short), 1, file);

		this->New(m_iWidth, m_iHeight);
		fread(m_pTiles,  sizeof(Tile), m_iWidth * m_iHeight, file);

		fclose(file);
		return true;
	}
	return false;
}

bool Map::Save(char const *filename) const
{
	FILE *file = fopen(filename, "wb");
	if (file != NULL) {
		fwrite(this->m_sName,    sizeof(char),	MAX_NAME, file);
		fwrite(&this->m_iWidth,  sizeof(short),	1, file);
		fwrite(&this->m_iHeight, sizeof(short),	1, file);
		fwrite(this->m_pTiles,   sizeof(Tile),	m_iWidth * m_iHeight, file);

		fclose(file);
		return true;
	}
	return false;
}

void Map::SetName(char const *value)
{
	strncpy(m_sName, value, MAX_NAME);
	m_sName[MAX_NAME - 1] = '\0';
}
